package com.wuwei.elearning.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Texts;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.Question;
import com.wuwei.elearning.question.domain.QuestionSettingForDa42;
import com.wuwei.elearning.question.domain.QuestionSettingForDa42Sup;
import com.wuwei.elearning.question.mapper.QuestionMapper;
import com.wuwei.elearning.question.mapper.QuestionSettingForDa42Mapper;
import com.wuwei.elearning.question.mapper.QuestionSettingForDa42SupMapper;
import com.wuwei.elearning.question.service.SettingQuestionsService;
import com.wuwei.elearning.utils.word.QuestionToWord;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SettingQuestionsServiceImpl implements SettingQuestionsService {

    @Resource
    private QuestionSettingForDa42SupMapper questionSettingForDa42SupMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionToWord questionToWord;

    @Resource
    private QuestionSettingForDa42Mapper questionSettingForDa42Mapper;


    @Override
    public void setQuestions(String engine, String ata22Type)  {
        String testType = "";
        /*
        1.先拿到Da42考卷各子章节需要出多少道题，放到一个arrayList中
        2.再拿到Da42所有的考题
        3.根据Da42各子章节需求出题的数量出题，出完再放到一个考卷arrayList中
        4.将考卷arrayList中的题目写到一个docx文件中
        5.将写好的docx文件地址返回给controller层，由controller层返回给前端
         */
        //1.先拿到Da42考卷各子章节需要出多少道题，放到一个arrayList中
        LambdaQueryWrapper<QuestionSettingForDa42> queryWrapper = new LambdaQueryWrapper<>();
        if (engine.equals("E4")) {
            queryWrapper.eq(QuestionSettingForDa42::getType,1);
            testType = "Austro E4";
        } else if (engine.equals("TAE")) {
            queryWrapper.eq(QuestionSettingForDa42::getType,0);
            testType = "Technify  TAE  125";
        } else {
            throw new ElearningMysqlException(20001,"发动机类型必须是E4或TAE！");
        }
        List<QuestionSettingForDa42> da42SettingList = questionSettingForDa42Mapper.selectList(queryWrapper);

        //2.再拿到Da42对应子章节的考题
        LambdaQueryWrapper<Question> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Question::getSubject,"DA42机型全程班");
        List<Question> questionsList = questionMapper.selectList(queryWrapper1);

        List<Question> setQuestionList = new ArrayList<>();
        da42SettingList.forEach(a->{
            String ataSubchapter = a.getAtaSubchapter();
            Integer questionsNum = a.getQuestionsNum();
            //2.1根据发动机类型把这个类型的发动机的题
            Question[] questions = questionsList.stream().filter(q -> {
                String chapter = q.getChapter();
                String substring = chapter.substring(0, 2);
                String lastChar = substring.substring(1, 2);
                String firstChar = substring.substring(0, 1);
                int chapterIndex = 0;
                if ("-".equals(lastChar)) {
                    chapterIndex = Integer.parseInt(firstChar);
                } else {
                    chapterIndex = Integer.parseInt(substring);
                }
                //如果ATA章节号小于61
                if (chapterIndex < 61) {
                    return ataSubchapter.equals(q.getSubChapter());
                } else {

                    return ((ataSubchapter.equals(q.getSubChapter())) && (chapter.contains(engine)));
                }
            }).filter(q -> {
                //2.2根据ata22的类型将不属于该系统的题去除掉
                String chapter = q.getChapter();
                String subChapter = q.getSubChapter();
                String substring = chapter.substring(0, 2);
                String lastChar = substring.substring(1, 2);
                String firstChar = substring.substring(0, 1);
                int chapterIndex = 0;
                if ("-".equals(lastChar)) {
                    chapterIndex = Integer.parseInt(firstChar);
                } else {
                    chapterIndex = Integer.parseInt(substring);
                }
                if (chapterIndex == 22) {
                    return subChapter.contains(ata22Type);
                }
                return true;
            }).toArray(Question[]::new);
            int length = questions.length;

            if (length != 0) {
                Random random = new Random();
                Set<Integer> set = new HashSet<>();
                while (set.size() < questionsNum) {
                    int index = random.nextInt(length);
                    if (!set.contains(index)) {
                        set.add(index);
                    }
                }
                for (int num : set) {
                    Question questionForDa42 = questions[num];
//                    //将出好的题放到一个新的arrayList中
                    setQuestionList.add(questionForDa42);
                }
            }
        });
        questionToWord.writeToBeDocxForTable(setQuestionList,testType);
    }

    /**
     * TAE补E4的题库
     */
    @Override
    public void settingDa42Sup() {
        String testType = "Austro E4";
        //构造一个返回参数的数组
        List<Question> setQuestionList = new ArrayList<>();
        //获取所有题目需要出几道题
        LambdaQueryWrapper<QuestionSettingForDa42Sup> qw = new LambdaQueryWrapper<>();
        List<QuestionSettingForDa42Sup> list = questionSettingForDa42SupMapper.selectList(qw);
        //获取所有题目
        LambdaQueryWrapper<Question> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(Question::getSubject,"DA42机型TEA补AE班");
        List<Question> questionList = questionMapper.selectList(qw1);
        //遍历所有题目设置

        for (int i = 0; i < list.size(); i++) {
            QuestionSettingForDa42Sup a = list.get(i);
            String  ataChapter = a.getAtaChapter().toString();
            //根据ata章节号查询能设置的题目
            List<Question> collect = questionList.stream()
                    .filter(question -> question.getChapter().equals(ataChapter))
                    .collect(Collectors.toList());
            //随机出题，length是一共有多少道题，从length中抽取questionsNum数量的数，要求不能重复
            //利用set去重的性质，进行随机出题，保证出到的题目没有重复的
            int length = collect.size();
            if (length>0) {
                Integer questionsNum = a.getQuestionNum();
                //拿到题目根据questionNum抽取questionNum数量的题目
                Random random = new Random();
                Set<Integer> set = new HashSet<>();
                while (set.size() < questionsNum) {
                    int index = random.nextInt(length);
                    set.add(index);
                }
                for (int num : set) {
                    Question questionForDa42Sup = collect.get(num);
//                    //将出好的题放到一个新的arrayList中
                    setQuestionList.add(questionForDa42Sup);
                }
            }
        }

        questionToWord.writeToBeDocxForTable(setQuestionList,testType);
    }
}
